//
//  PressViewController.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/25/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "PressViewController.h"
#import "PressCell.h"
#import "PhotoDetailViewController.h"
#import "MainViewController.h"
#import "PressItem.h"
#import "MyFile.h"
#import "Request.h"
#import "Response.h"
#import "ZipArchive.h"

#import "PhotoWall.h"

#define part_tag 10001
#define sumit_tag 2222

@interface PressViewController ()

@end

@implementation PressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self calculateRemindBtnFrame:[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"]];
    [self initMarkData];
    
    [theLocation startUpdatingLocation];
    [self locationTip];
}

-(void)viewDidDisappear:(BOOL)animated
{
    
    [super viewDidDisappear:animated];
    imagePicker = nil;
    imagePicker.delegate = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.titleLabel.text = _titleString;
    _photoCount = 0;
    self.pressItem = [[PressItem alloc] init];
    _pressItem.breviaryphotos = [[NSMutableArray alloc] init];
    _pressItem.photphotos = [[NSMutableArray alloc] init];
 
    theLocation = [CLLocationManager new];
    theLocation.delegate = self;
    theLocation.distanceFilter = 100;
    
    timeString = [[NSString alloc] init];
    location = [[NSString alloc] init];
    location_gps = [[NSString alloc] init];
    
    //假数据的测试
    self.myArray = [NSMutableArray arrayWithCapacity:3];
    bgArrary = [NSMutableArray arrayWithCapacity:3];
//    for (int i=0; i<10; i++) {
//        
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",4]];
//        [self.myArray addObject:image];
//
//    }
    
    [self initPressViews];
    //相册缩略图
    [self initPhotoScrollView];
    [self getWallDatas];//获取照片数据
}

#pragma mark ==================UI Create==================
-(void)initPressViews
{
    //文字信息列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 20, 1024-20, 112/2.0f*5) style:UITableViewStylePlain];
    _tableView.delegate =self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.bounces =NO;
    [self.contentView addSubview:_tableView];

    //照相按钮
    photoBtn = [UIButton initButton:CGRectMake(9, height_y(_tableView)+116/2.0f, mPress_Addphoto_Normal_Img.size.width, mPress_Addphoto_Normal_Img.size.height) btnNorImage:mPress_Addphoto_Normal_Img btnPressBtn:mPress_Addphoto_Highlight_Img btnTitle:@"照片" titleColor:[UIColor whiteColor] titleFont:[UIFont boldSystemFontOfSize:17]];
    [photoBtn setTitleEdgeInsets:UIEdgeInsetsMake(112, 0, 0, 0)];
    [photoBtn addTarget:self action:@selector(goCamera) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:photoBtn];
    
   
    
    //两个返回按钮
    UIButton * backBtn1 = [UIButton initButton:CGRectMake(567/2.0f,height_y(photoBtn)+83/2.0f,mPress_sumit1_Normal_Img.size.width, mPress_sumit1_Normal_Img.size.height) btnNorImage:mPress_sumit1_Normal_Img btnPressBtn:mPress_sumit1_Select_Img btnTitle:nil titleColor:nil titleFont:nil];
    [backBtn1 addTarget:self action:@selector(sumitClick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn1.tag = sumit_tag+1;
    [self.contentView addSubview:backBtn1];

    UIButton * backBtn2 = [UIButton initButton:CGRectMake(width_x(backBtn1)+173/2.0f,height_y(photoBtn)+83/2.0f,mPress_sumit2_Normal_Img.size.width, mPress_sumit2_Normal_Img.size.height) btnNorImage:mPress_sumit2_Normal_Img btnPressBtn:mPress_sumit2_Select_Img btnTitle:nil titleColor:nil titleFont:nil];
    [backBtn2 addTarget:self action:@selector(sumitClick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn2.tag = sumit_tag+2;
    [self.contentView addSubview:backBtn2];

}

-(void)createPartView:(UIView *)view
{
    view.userInteractionEnabled =YES;
    //顶部按钮
    upButton = [UIButton initButton:CGRectMake(0,(mPress_Cell_Height-1-22.5)/2.0f, 22.5, 22.5) btnNorImage:mPress_Part_Normal_Img btnSelectBtn:mPress_Part_Select_Img btnTitle:nil titleNorColor:nil titleSelectColor:nil titleFont:nil];
    [upButton addTarget:self action:@selector(choosePart:) forControlEvents:UIControlEventTouchDown];
    upButton.tag =part_tag+1;
    [view addSubview:upButton];
    
    //顶部Label
    UILabel * upLabel = [UILabel initLabel:CGRectMake(width_x(upButton)+7, 0, 40, mPress_Cell_Height-1) textFont:mPress_Text_Font textColor:mPress_Content_Color textAlignment:NSTextAlignmentLeft];
    upLabel.text = @"顶部";
    [view addSubview:upLabel];
    
    //中部
    midButton = [UIButton initButton:CGRectMake(width_x(upButton)+55,(mPress_Cell_Height-1-22.5)/2.0f, 22.5, 22.5) btnNorImage:mPress_Part_Normal_Img btnSelectBtn:mPress_Part_Select_Img btnTitle:nil titleNorColor:nil titleSelectColor:nil titleFont:nil];
    [midButton addTarget:self action:@selector(choosePart:) forControlEvents:UIControlEventTouchDown];
    midButton.tag =part_tag+2;
    [view addSubview:midButton];
    
    //中部Label
    UILabel * midLabel = [UILabel initLabel:CGRectMake(width_x(midButton)+7, 0, 40, mPress_Cell_Height-1) textFont:mPress_Text_Font textColor:mPress_Content_Color textAlignment:NSTextAlignmentLeft];
    midLabel.text =@"中部";
    [view addSubview:midLabel];
    
    //底部
    footButton = [UIButton initButton:CGRectMake(width_x(midButton)+113/2.0f,(mPress_Cell_Height-1-22.5)/2.0f, 22.5, 22.5) btnNorImage:mPress_Part_Normal_Img btnSelectBtn:mPress_Part_Select_Img btnTitle:nil titleNorColor:nil titleSelectColor:nil titleFont:nil];
    [footButton addTarget:self action:@selector(choosePart:) forControlEvents:UIControlEventTouchDown];
    footButton.tag =part_tag+3;
    [view addSubview:footButton];
    
    //底部Label
    UILabel * footLabel = [UILabel initLabel:CGRectMake(width_x(footButton)+7, 0, 50, mPress_Cell_Height-1) textFont:mPress_Text_Font textColor:mPress_Content_Color textAlignment:NSTextAlignmentLeft];
    footLabel.text = @"底部";
    [view addSubview:footLabel];
    
    //其他label
    UILabel * otherLabel = [UILabel initLabel:CGRectMake(width_x(footButton)+152/2.0f, 0, 40, mPress_Cell_Height-1) textFont:mPress_Text_Font textColor:mPress_Content_Color textAlignment:NSTextAlignmentLeft];
    otherLabel.text = @"其他";
    [view addSubview:otherLabel];
    
    //"其他"输入框背景图片
    UIImageView * otherBgView = [[UIImageView alloc] initWithFrame:CGRectMake(width_x(footButton)+234/2.0f,  (mPress_Cell_Height-29)/2.0f, 316/2.0f, 29)];
    otherBgView.image = [XDTools stretchableImag:mPress_Mark_Wireframe_Img];
    otherBgView.userInteractionEnabled = YES;
    [view addSubview:otherBgView];
    
    //"其他"textfiled
    partTextField = [[UITextField alloc] initWithFrame:otherBgView.bounds];
    partTextField.backgroundColor = [UIColor redColor];
    partTextField.font = [UIFont systemFontOfSize:15];
    partTextField.backgroundColor = [UIColor clearColor];
    partTextField.clearButtonMode = UITextFieldViewModeAlways;
    partTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    partTextField.delegate = self;
    [otherBgView addSubview:partTextField];
    
}


-(void)initMarkData
{
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"备注-->数据库打开失败");
        return;
    }
    FMResultSet * rs = [db executeQuery:@"SELECT * FROM T_TRACE_SUPERVISION WHERE assert_id = ?",[[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"id"]];
    while ([rs next]) {
        markString = [rs objectForColumnName:@"notes"];
    }
    [db close];
}

-(void)initPhotoScrollView{
    myScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(photoBtn.frame.origin.x+photoBtn.frame.size.width+15, photoBtn.frame.origin.y-13, 800, 215)];
    myScrollView.bounces = NO;
    myScrollView.pagingEnabled = YES;
    myScrollView.delegate = self;
    myScrollView.backgroundColor = [UIColor whiteColor];
    myScrollView.userInteractionEnabled = YES;
    myScrollView.showsHorizontalScrollIndicator=NO;
    myScrollView.showsVerticalScrollIndicator= NO;
    myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width * [self.myArray count],myScrollView.frame.size.height);
    myScrollView.contentOffset = CGPointMake(0, 0);
    myScrollView.hidden = NO;
    [self.contentView addSubview:myScrollView];
    
    recycledPages=[[NSMutableSet alloc] init];
    visiblePages =[[NSMutableSet alloc] init];

   
}
#pragma mark ==================UITableView Delegagte=====================
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 112/2.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cell";
    PressCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if(cell == nil){
        cell = [[PressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row%2){
        cell.diselectBg.image = mPress_Cell_Odd_Img;
    }else{
        cell.diselectBg.image = mPress_Cell_Even_Img;
    }
    cell.firstLabel.text=[[self.press_ifo_array objectAtIndex:indexPath.row] objectAtIndex:0];
    cell.thirdLabel.text= [[self.press_ifo_array objectAtIndex:indexPath.row] objectAtIndex:1];
    
    if(indexPath.row == 0){
        cell.secondLabel.text = [[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"code"];
        cell.fourthLabel.text = [[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"name"];
        
    }else if(indexPath.row == 1){
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//@"MMM d, h:mm a"];
        NSString *lastUpdated = [NSString stringWithFormat:@"%@",
                                 [formatter stringFromDate:[NSDate date]]];
        timeString = lastUpdated;
        cell.secondLabel.text = [[XDTools sharedXDTools] intervalSinceNow:timeString];
        cell.fourthLabel.text = [[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"supervision_linkman"];
    }
    
    if (indexPath.row == 2){
        //地址label
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(204, 1, 1004-205, mPress_Cell_Height-1)];
        view.backgroundColor = [UIColor whiteColor];
        [cell addSubview:view];
        addressLabel = [UILabel initLabel:view.bounds textFont:mPress_Text_Font textColor:mPress_Content_Color textAlignment:NSTextAlignmentLeft];
        addressLabel.backgroundColor = [UIColor clearColor];
        [view addSubview:addressLabel];

//        NSString * location = [[NSUserDefaults standardUserDefaults] valueForKey:@"location"];
//        NSString * location_gps = [[NSUserDefaults standardUserDefaults] valueForKey:@"location_gps"];
        if (IS_NOT_EMPTY(location)){
            addressLabel.text = location;
        }else{
            if (IS_NOT_EMPTY(location_gps)){
                addressLabel.text = location_gps;
            }else{
                addressLabel.text = @"";
            }
        }

        CGRect rect = [XDTools xyAutoSizeOfWidget:addressLabel andSize:CGSizeMake(1004-204-60, mPress_Cell_Height-1) andtextFont:15];
        addressLabel.frame = CGRectMake(rect.origin.x, 0,rect.size.width, mPress_Cell_Height-1);
        //定位按钮
        positionBtn = [UIButton initButton:CGRectMake(width_x(addressLabel)+10, (mPress_Cell_Height-75/2.0f)/2.0f, 75/2.0f, 75/2.0f) btnNorImage:mPress_Position_Normal_Img btnPressBtn:mPress_Position_Highlight_Img btnTitle:nil titleColor:nil titleFont:nil];
        [positionBtn addTarget:self action:@selector(positionClick:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:positionBtn];
    }else if (indexPath.row == 3){
        //贴签位置背景
        UIView * partBgView = [[UILabel alloc] initWithFrame:CGRectMake(204,1, 1004-204-60, mPress_Cell_Height-1)];
        partBgView.backgroundColor = RGBA(238, 247, 254);
        [cell addSubview:partBgView];
        
        [self createPartView:partBgView];
    

    }else if (indexPath.row == 4){
        //备注背景
        UIView * markBgView = [[UILabel alloc] initWithFrame:CGRectMake(204,1, 1004-204-60, mPress_Cell_Height-1)];
        markBgView.backgroundColor = [UIColor whiteColor];
        [cell addSubview:markBgView];
        
        UIImageView * markWireFrameBg = [[UIImageView alloc] init];
        markWireFrameBg.frame = CGRectMake(204, (mPress_Cell_Height-29)/2.0f, 938/2.0f, 29);
        markWireFrameBg.image = [XDTools stretchableImag:mPress_Mark_Wireframe_Img];
        markWireFrameBg.userInteractionEnabled =YES;
        [cell addSubview:markWireFrameBg];
        
        //备注
        marktextField = [[UITextField alloc] initWithFrame:markWireFrameBg.bounds];
        marktextField.font = [UIFont systemFontOfSize:15];
        marktextField.backgroundColor = [UIColor clearColor];
        marktextField.clearButtonMode = UITextFieldViewModeAlways;
        marktextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        marktextField.delegate = self;
        marktextField.text = markString;
        [markWireFrameBg addSubview:marktextField];
    
}
    return cell;
}


#pragma mark ====================UITextFeild Delegate==============
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == partTextField){
        upButton.selected =NO;
        midButton.selected =NO;
        footButton.selected =NO;
    }
}

#pragma mark =====================UIButtion Click==================
//重新定位
-(void)positionClick:(UIButton *)button
{
    [theLocation startUpdatingLocation];
    [self locationTip];
    
    DDLOG_CURRENT_METHOD;
}

//选择贴签部位
-(void)choosePart:(UIButton *)buttion
{
    partTextField.text = nil;
    [partTextField resignFirstResponder];
    if(buttion.tag-part_tag==1){
        upButton.selected = !upButton.selected;
        midButton.selected =NO;
        footButton.selected =NO;
    }
    
    if(buttion.tag-part_tag==2){
        upButton.selected = NO;
        midButton.selected =!midButton.selected;
        footButton.selected =NO;
    }
    
    if(buttion.tag-part_tag==3){
        upButton.selected = NO;
        midButton.selected =NO;
        footButton.selected =!footButton.selected;
    }
}

-(void)sumitClick:(UIButton *)button
{
    [self processTheData:button];
    
}

#pragma mark =====================重写 返回方法==================
-(void)backBtnClick
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark =================提交时，数据处理=====================
-(void)processTheData:(UIButton *)button
{
    _pressItem.assert_id = [[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"id"];
    _pressItem.name = [[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"name"];
    _pressItem.assert_code = [[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"code"];
    _pressItem.propertyWithlabel_record_id = [[XDTools sharedXDTools] gen_uuid];
    _pressItem.tag_code = _titleString;
 
    if (upButton.selected){
        _pressItem.part = @"顶部";
    }else if (midButton.selected){
        _pressItem.part = @"中部";
    }else if (footButton.selected){
        _pressItem.part = @"底部";
    }else{
        _pressItem.part = partTextField.text;
    }
    
    PressCell * cell =(PressCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    _pressItem.create_time =timeString;
    
    _pressItem.supervision_record_id = [[XDTools sharedXDTools] gen_uuid];
    _pressItem.notes =marktextField.text;
    
    _pressItem.scan_record_id = [[XDTools sharedXDTools] gen_uuid];;
    _pressItem.scan_time = timeString;
    _pressItem.scan_location_gps = addressLabel.text;
    _pressItem.scan_location = addressLabel.text;
    _pressItem.scan_device = [UserInfo sharedUserInfo].scan_device;
    _pressItem.scan_devicename = [UserInfo sharedUserInfo].scan_devicename;
    _pressItem.scan_userid =[UserInfo sharedUserInfo].userid;
    _pressItem.scan_username = [UserInfo sharedUserInfo].username;
    _pressItem.scan_status = @"监造";
    
    NSMutableString * breviaryphotoString = [[NSMutableString alloc] init];
    NSMutableString * photphotoStirng = [[NSMutableString alloc] init];
    for (int i = 0 ; i <[_pressItem.breviaryphotos count];i++){
        if (i<[_pressItem.breviaryphotos count]-1){
            [breviaryphotoString appendString:[NSString stringWithFormat:@"%@,",[_pressItem.breviaryphotos objectAtIndex:i]]];
        }else{
            [breviaryphotoString appendString:[_pressItem.breviaryphotos objectAtIndex:i]];
        }
    }
    
    for (int i =0; i<[_pressItem.photphotos count];i++){
        if (i<[_pressItem.photphotos count]-1){
            [photphotoStirng appendString:[NSString stringWithFormat:@"%@,",[_pressItem.photphotos objectAtIndex:i]]];
        }else{
            [photphotoStirng appendString:[_pressItem.photphotos objectAtIndex:i]];
        }
    }

    NSString * aPath = [XDTools databaseFilePath];
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
    [queue inTransaction:^(FMDatabase * db, BOOL * rollback) {
        BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_ASSERTS_TAG VALUES(?,?,?,?,?)",_pressItem.propertyWithlabel_record_id,_pressItem.assert_id,_pressItem.tag_code,_pressItem.part,_pressItem.create_time];
        if (!a){
            * rollback =YES;
            return;
        }
        
        BOOL b = [db executeUpdate:@"INSERT INTO T_TRACE_SUPERVISION VALUES(?,?,?)",_pressItem.supervision_record_id,_pressItem.assert_id,_pressItem.notes];
        if(!b){
            * rollback =YES;
            return;
        }
        
        BOOL c = [db executeUpdate:@"INSERT INTO T_TRACE_SCAN_LOG VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",_pressItem.scan_record_id,_pressItem.assert_id,_pressItem.tag_code,_pressItem.scan_time,_pressItem.scan_location_gps,_pressItem.scan_location,_pressItem.scan_device,_pressItem.scan_devicename,_pressItem.scan_userid,_pressItem.scan_username,_pressItem.scan_status,breviaryphotoString,photphotoStirng,cell.fourthLabel.text];
        if (!c){
            * rollback =YES;
            return;
        }

    }];
    
    [[XDTools sharedXDTools].mvc initHomePageDatas:nil];
    
    if ([XDTools NetworkReachable]){
        Request* req = [[Request alloc] init];
        NSMutableDictionary * data =[self adjustmentContentJson];
        //客户端生成的文件都应该用uuid命名，并使文件名和数据表中存储的文件名保持一致
        
        //此处因将多个文件压缩成一个zip文件
        NSString * string1 = IMG_FILESAVEPATH;
        NSString *photphotoFile = [string1 stringByAppendingPathComponent:@"photphotoFile.zip"];
        NSString * breviaryphotoFile = [string1 stringByAppendingPathComponent:@"breviaryphotoFile.zip"];
        ZipArchive * zaPhotphoto = [[ZipArchive alloc] init];
        ZipArchive * zaBreviaryphoto = [[ZipArchive  alloc] init];
        [zaPhotphoto CreateZipFile2:photphotoFile];
        [zaBreviaryphoto CreateZipFile2:breviaryphotoFile];
        for (int i = 0 ; i < [_pressItem.photphotos count];i++){
            NSRange range = [[_pressItem.photphotos objectAtIndex:i] rangeOfString:@"law_"];
            NSString * string =[[_pressItem.photphotos objectAtIndex:i] substringFromIndex:range.location];
            [zaPhotphoto addFileToZip:[_pressItem.photphotos objectAtIndex:i] newname:string];
        }
        BOOL success = [zaPhotphoto CloseZipFile2];
        DDLOG(@"Zipped file with result %d",success);
        
        for (int i = 0 ;i <[_pressItem.breviaryphotos count];i++){
            NSRange range = [[_pressItem.breviaryphotos objectAtIndex:i] rangeOfString:@"thum_"];
            NSString * string =[[_pressItem.breviaryphotos objectAtIndex:i] substringFromIndex:range.location];
            [zaBreviaryphoto addFileToZip:[_pressItem.breviaryphotos objectAtIndex:i] newname:string];
        }
        BOOL success2 = [zaBreviaryphoto CloseZipFile2];
        DDLOG(@"Zipped file with result %d",success2);
        
        MyFile * f1 = [[MyFile alloc] init];
        NSString * fileName1 = @"breviaryphotoFile.zip";
        f1.path = [string1 stringByAppendingPathComponent:fileName1];
        f1.name = fileName1;
        f1.length = [[XDTools sharedXDTools] fileSizeAtPath:f1.path];
        
        MyFile * f2 = [[MyFile alloc] init];
        NSString * fileName2 = @"photphotoFile.zip";
        f2.path = [string1 stringByAppendingPathComponent:fileName2];
        f2.name = fileName2;
        f2.length = [[XDTools sharedXDTools] fileSizeAtPath:f2.path];
        
        NSArray * fileArray = [[NSArray alloc] initWithObjects:f1,f2, nil];
        
        NSArray * postData = [[NSArray alloc] initWithObjects:data, nil];
        [XDTools showProgress:[UIApplication sharedApplication].keyWindow];
        [req uploadFile:mTrace_Upsupervisiondatas keyValue:(NSDictionary *)postData file:fileArray progressObserver:self completionHandler:^(ResponseData *datas) {
            if ([datas.result intValue]==1){
                [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
                [XDTools showTips:@"提交成功" toView:[UIApplication sharedApplication].keyWindow];
                [self performSelector:@selector(backtypes:) withObject:button afterDelay:1.5];
            }else{
                [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
                [XDTools showTips:datas.errorMsg toView:[UIApplication sharedApplication].keyWindow];
            }
        }];
    }else{
        FMDatabase * db = [XDTools getDb];
        if (![db open]){
            DDLOG(@"提交页面-->待提交页面表-->数据库打开失败");
            return;
        }
        BOOL a = [db executeUpdate:@"INSERT INTO T_TRACE_SUMIT VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_pressItem.assert_id,_pressItem.propertyWithlabel_record_id,_pressItem.tag_code,_pressItem.part,_pressItem.create_time,_pressItem.supervision_record_id,_pressItem.notes,_pressItem.scan_record_id,_pressItem.scan_time,_pressItem.scan_location_gps,_pressItem.scan_location,_pressItem.scan_device,_pressItem.scan_devicename,_pressItem.scan_userid,_pressItem.scan_username,_pressItem.scan_status,breviaryphotoString,photphotoStirng,_pressItem.name,_pressItem.assert_code];
        if (!a){
            DDLOG(@"提交页面-->插入待提交页面表-->插入失败");
            return;
        }
        [db close];
        
        NSString * countstring =  [[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"];
        int count = [countstring intValue];
        count++;
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",count] forKey:@"waitCunitCount"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self calculateRemindBtnFrame:[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"]];
//        int count = [[XDTools sharedXDTools].waitCumitCount intValue];
//        count++;
//        [XDTools sharedXDTools].waitCumitCount = [NSString stringWithFormat:@"%d",count];
        [XDTools showTips:@"保存至待提交队列" toView:[UIApplication sharedApplication].keyWindow];
        [self performSelector:@selector(backtypes:) withObject:button afterDelay:1.5];
    }
}

-(void)backtypes:(UIButton *)button
{
    if(button.tag == sumit_tag+1){
        [self backBtnClick];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark ==================调整成content_json 格式===================
-(NSMutableDictionary * )adjustmentContentJson
{
    NSDictionary * asserttagDict = [[NSDictionary alloc] initWithObjectsAndKeys:_pressItem.propertyWithlabel_record_id,@"id",_pressItem.tag_code,@"tag_code",_pressItem.part,@"part",_pressItem.create_time,@"create_time", nil];
    
    NSDictionary * supervisionDict;
    if (IS_NOT_EMPTY(_pressItem.notes)){
        supervisionDict = [[NSDictionary alloc] initWithObjectsAndKeys:_pressItem.supervision_record_id,@"id",_pressItem.notes,@"notes",nil];
    }else{
        supervisionDict = [[NSDictionary alloc] initWithObjectsAndKeys:_pressItem.supervision_record_id,@"id", nil];
    }
    
    NSMutableDictionary * photosDict = [[NSMutableDictionary alloc] init];
    
    NSMutableArray * marray1 = [[NSMutableArray alloc] init];
    for (int i =0;i<[_pressItem.breviaryphotos count];i++){
        NSRange range = [[_pressItem.breviaryphotos objectAtIndex:i] rangeOfString:@"thum_"];
        NSString * string =[[_pressItem.breviaryphotos objectAtIndex:i] substringFromIndex:range.location];
        [marray1 addObject:string];
    }
    
    NSMutableArray * marray2 = [[NSMutableArray alloc] init];
    for (int i =0;i<[_pressItem.photphotos count];i++){
        NSRange range = [[_pressItem.photphotos objectAtIndex:i] rangeOfString:@"law_"];
        NSString * string =[[_pressItem.photphotos objectAtIndex:i] substringFromIndex:range.location];
        [marray2 addObject:string];
    }
    
    [photosDict setValue:marray1 forKey:@"breviaryphotos"];
    [photosDict setValue:marray2 forKey:@"photphotos"];
    
    NSMutableDictionary * scanDict = [[NSMutableDictionary alloc] init];
    [scanDict setValue:_pressItem.scan_record_id forKey:@"id"];
    [scanDict setValue:_pressItem.tag_code forKey:@"tag_code"];
    [scanDict setValue:_pressItem.scan_time forKey:@"scan_time"];
    [scanDict setValue:_pressItem.scan_location_gps forKey:@"scan_location_gps"];
    [scanDict setValue:_pressItem.scan_location forKey:@"scan_location"];
    [scanDict setValue:_pressItem.scan_device forKey:@"scan_device"];
    [scanDict setValue:_pressItem.scan_devicename forKey:@"scan_devicename"];
    [scanDict setValue:_pressItem.scan_userid forKey:@"scan_userid"];
    [scanDict setValue:_pressItem.scan_username forKey:@"scan_username"];
    [scanDict setValue:_pressItem.scan_status forKey:@"scan_status"];
    [scanDict setValue:photosDict forKey:@"photos"];
    
    NSMutableArray * assertArray = [[NSMutableArray alloc] init];
    [assertArray addObject:asserttagDict];
    
    NSMutableArray * supervisionArray = [[NSMutableArray alloc] init];
    [supervisionArray addObject:supervisionDict];
    
    NSMutableArray * scanArray = [[NSMutableArray alloc] init];
    [scanArray addObject:scanDict];
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    [dict setValue:assertArray forKey:@"asserttag"];
    [dict setValue:supervisionArray forKey:@"supervision"];
    [dict setValue:scanArray forKey:@"scan"];
    
    NSMutableDictionary * data = [[NSMutableDictionary alloc] init];
    [data setValue:_pressItem.assert_id forKey:@"assert_id"];
    [data setValue:dict forKey:@"data"];
    
    return data;
}


- (void)createImageViews
{
    for (int i=0; i<self.myArray.count; i++) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToPhotos:)];
        ImageView * page = [[ImageView alloc]init];
        page.tag = 1000+i;
        [page addGestureRecognizer:tap];
        [self configurePage:page forIndex:i];
        [myScrollView addSubview:page];
    }
}
#pragma mark-scrollView重用机制-
- (void)tilePages
{
    // Calculate which pages are visible
    CGRect visibleBounds =myScrollView.bounds;
    int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    int lastNeededPageIndex  = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds));
    firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
    lastNeededPageIndex  = MIN(lastNeededPageIndex, [self.myArray count] - 1);
    
    // Recycle no-longer-visible pages
    for (ImageView *page in visiblePages) {
        if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
            [recycledPages addObject:page];
            [page removeFromSuperview];
        }
    }
    [visiblePages minusSet:recycledPages];
    
    // add missing pages
    for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) {
            ImageView *page = [self dequeueRecycledPage];
            if (page == nil) {
                page = [[ImageView alloc] init];
            }
            [self configurePage:page forIndex:index];
            [myScrollView addSubview:page];
            [visiblePages addObject:page];
        }
    }
}

- (ImageView *)dequeueRecycledPage
{
    ImageView *page = [recycledPages anyObject];
    if (page) {
        [recycledPages removeObject:page];
    }
    return page;
}

- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
    BOOL foundPage = NO;
    for (ImageView *page in visiblePages) {
        if (page.index == index) {
            foundPage = YES;
            break;
        }
    }
    return foundPage;
}

- (void)configurePage:(ImageView *)page forIndex:(NSUInteger)index
{
    page.index = index;
    page.frame =CGRectMake( 10+264*index, 13, 254,190);
    page.backgroundColor = mApp_Bg_color;
//    [page initSuoLueTu:[self.myArray objectAtIndex:index]];
    [page initSmallView:[self.myArray objectAtIndex:index]];

    
}

-(void)goToPhotos:(UITapGestureRecognizer *)sender{
    PhotoDetailViewController *photoVC = [[PhotoDetailViewController alloc] init];
    photoVC.myArray = bgArrary;
    photoVC.isDefualt = NO;
    photoVC.contentOffset = sender.view.tag-1000;
    [self.navigationController pushViewController:photoVC animated:YES];
}


#pragma mark - CLLocation

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation * currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    if (![XDTools isValidCoordinate:coor]){
        return;
    }
    
    //latitude和lontitude均为NSString型变量
    //纬度
    NSString * latitude = [NSString  stringWithFormat:@"%.6f", coor.latitude];
    //经度
    NSString * longitude = [NSString stringWithFormat:@"%.6f",coor.longitude];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"(%@,%@)",latitude,longitude] forKey:@"location_gps"];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    

    [geocoder reverseGeocodeLocation: currentLocation completionHandler:^(NSArray *array, NSError *error) {
        
        if (array.count > 0) {
            
            CLPlacemark * vplacemark = [array objectAtIndex:0];
            NSString * sttr = [[vplacemark.addressDictionary objectForKey:@"FormattedAddressLines"] objectAtIndex:0];
            location = [NSString stringWithFormat:@"%@",sttr];
            location_gps = [NSString stringWithFormat:@"(%@,%@)",latitude,longitude];
            if (IS_NOT_EMPTY(location)){
                addressLabel.text = location;
            }else{
                if (IS_NOT_EMPTY(location_gps)){
                    addressLabel.text = location_gps;
                }else{
                    addressLabel.text = @"";
                }
            }
            CGRect rect = [XDTools xyAutoSizeOfWidget:addressLabel andSize:CGSizeMake(1004-204-60, mPress_Cell_Height-1) andtextFont:15];
            addressLabel.frame = CGRectMake(rect.origin.x, 0,rect.size.width, mPress_Cell_Height-1);
            positionBtn.frame=CGRectMake(width_x(addressLabel)+10, (mPress_Cell_Height-75/2.0f)/2.0f, 75/2.0f, 75/2.0f);
            [theLocation stopUpdatingLocation];
            [[NSUserDefaults standardUserDefaults] setValue:sttr forKey:@"location"];
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    DDLOG(@"XDAppDelegate:%@",@"localtion fail");
    [theLocation stopUpdatingLocation];
}

- (void)locationTip
{
    if (!([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied)) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位服务不可用"
                                                        message:@"建议开启定位服务(设置>定位服务>开启乐度定位服务)"
                                                       delegate:nil
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
}

//去照相
-(void)goCamera{
    if(_photoCount>4){
        [XDTools showTips:@"一次最多照5张" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
  UIImagePickerController*  imagePicker_ = [[UIImagePickerController alloc] init];
    imagePicker_.navigationBar.tintColor = [UIColor blackColor];
    imagePicker_.delegate = self;
    imagePicker_.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker_.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker_.allowsEditing = YES;
    [self presentViewController:imagePicker_ animated:YES completion:NULL];

}

#pragma mark ----------------imagePickerDelegate-----------------------------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    _photoCount++;
    myScrollView.contentOffset = CGPointMake(0, 0);
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    isPhotoHadEdit = YES;

    //头像
    isHeaderPhoto = NO;
    UIImage * image = [info objectForKey: @"UIImagePickerControllerEditedImage"];       //头像
    UIImage * image2 = [info objectForKey:@"UIImagePickerControllerOriginalImage"];     //相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
//    [self.myArray insertObject:image atIndex:0];
    myScrollView.hidden = NO;
    
    
    
    NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *uuid = [[XDTools sharedXDTools] gen_uuid];
    
	NSString  *rawPath = [cacheDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"law_%@.jpg",uuid]];//原图路径
    NSString *brePath = [cacheDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"thum_%@.jpg",uuid]];//缩略图路径
    [_pressItem.breviaryphotos addObject:brePath];
    [_pressItem.photphotos addObject:rawPath];


    UIImage * breImage = [XDTools imageByScalingAndCroppingForSize:CGSizeMake(250, 220) image:image];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:rawPath]) {
        DDLOG(@"%@",rawPath);
    }else{
        NSData *imageData = UIImageJPEGRepresentation(image2, 0.3);
        [manager createFileAtPath:rawPath contents:imageData attributes:nil];
    }
    
    if ([manager fileExistsAtPath:brePath]) {
        DDLOG(@"%@",brePath);
    }else{
        NSData *imageData = UIImageJPEGRepresentation(breImage, 0.5);
        [manager createFileAtPath:brePath contents:imageData attributes:nil];
    }
    [bgArrary insertObject:rawPath atIndex:0];
    [self.myArray insertObject:brePath atIndex:0];
    [self tilePages];
    [self createImageViews];
    
    [photoBtn setTitle:[NSString stringWithFormat:@"照片(%d)",[bgArrary count]] forState:UIControlStateNormal];
    myScrollView.contentSize = CGSizeMake(264 * [self.myArray count],myScrollView.frame.size.height);

    
//    headerView.image = [UIImage imageNamed:@"User_profile_default_detail_head"];
    

}

//获取照片墙数据
-(void)getWallDatas{
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"数据打开失败");
        return;
    }
    FMResultSet * rs = [db executeQuery:@"SELECT * FROM T_TRACE_SCAN_LOG where assert_id = ?",[[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"id"]];
    while ([rs next]) {
        PhotoWall *wall = [[PhotoWall alloc] init];
        wall.bgUrlString = [rs objectForColumnName:@"photphoto"];
        wall.state = [rs objectForColumnName:@"status"];
        wall.time = [rs objectForColumnName:@"scan_time"];
        wall.urlString = [rs objectForColumnName:@"breviaryphoto"];
        wall.tag_code = [rs objectForColumnName:@"tag_code"];
        FMResultSet *rs2 = [db executeQuery:@"SELECT * FROM T_TRACE_ASSERTS_TAG where assert_id = ? and tag_code = ?",[[XDTools sharedXDTools].mvc.mDictionary valueForKey:@"id"],wall.tag_code];
        while ([rs2 next]) {
            wall.location = [rs2 objectForColumnName:@"part"];
        }
        
        [self handleWallDatas:wall.urlString wall:wall];
        [self saveBgUrl:wall.bgUrlString];
        DDLOG(@"缩略图: urlstring = %@,\n原图: bgUrlString = %@",wall.urlString,wall.bgUrlString);
    }
    if ([self.myArray count]>0) {
        
        [self tilePages];
        //
        [self createImageViews];
    }
    [db close];
}

-(void)handleWallDatas:(NSString *)urlS wall:(PhotoWall *)w{
    if (!IS_NOT_EMPTY(urlS)) {
        //        urlS = @"";
        //        PhotoWall *wall = [[PhotoWall alloc] initUrlString:urlS time:w.time location:w.location state:w.state];
        //        wall.tag_code = w.tag_code;
        //        [dataArrary addObject:wall];
        //        DDLOG(@"---------------%@,%@,%@,%@,%@",wall.urlString,wall.time,wall.state,wall.location,wall.tag_code);
    }else{
        NSArray *arrary = [urlS componentsSeparatedByString:@","];
        for (int i = 0; i<[arrary count]; i++) {
            PhotoWall *wall = [[PhotoWall alloc] initUrlString:[arrary objectAtIndex:i] time:w.time location:w.location state:w.state];
            wall.tag_code = w.tag_code;
            [self.myArray addObject:wall.urlString];
            DDLOG(@"---------------%@,%@,%@,%@,%@",wall.urlString,wall.time,wall.state,wall.location,wall.tag_code);
            
        }
        myScrollView.contentSize = CGSizeMake(264 * [self.myArray count],myScrollView.frame.size.height);
    }
}
//存储大图的url
-(void)saveBgUrl:(NSString *)urlStr{
    if (!IS_NOT_EMPTY(urlStr)) {
        //        urlStr = @"";
        //        [bgUrlArrary addObject:urlStr];
    }else{
        NSArray *arrary = [urlStr componentsSeparatedByString:@","];
        [bgArrary addObjectsFromArray:arrary];
        
        [photoBtn setTitle:[NSString stringWithFormat:@"照片(%d)",[bgArrary count]] forState:UIControlStateNormal];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
